<?php
namespace app\home\controller;

use app\common\model\User as UserModel;
use app\common\controller\HomeBase;
use think\Db;
use think\Config;
use think\Cache;

/**
 * Payment
 * Class Payment
 */
class Payment extends HomeBase
{

    protected function _initialize()
    {
        parent::_initialize();
        $this->getPayConfig();
    }

    /**
     * 获取支付配置信息
     */
    protected function getPayConfig()
    {
        if (Cache::has('pay_config')) {
            $pay_config = Cache::get('pay_config');
        } else {
            $pay_config = Db::name('system')->field('value')->where('name', 'pay_config')->find();
            $pay_config = unserialize($pay_config['value']);
            Cache::set('pay_config', $pay_config);
        }
        $this->pay_config = $pay_config;
    }
	/**
     * 异步回调处理
     * @return mixed
     */
    public function notify()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            // 支付成功处理
            if ($data['orderStatus'] == 'PAY_SUC') {
                // 赋值新数组，签名字符串用
                $new_data = $data;
                // 获取签名
                $sign = $data['sign'];
                // 去掉签名进行排序
                unset($new_data['sign']);
                // 数组排序
                ksort($new_data);
                // 字符串处理
                $str = '';
                foreach ($new_data as $k => $v) {
                    $str .= $k ."=". $v."&";
                }
                // 处理好的字符串
                $str = substr($str, 0, -1);
                //验证签名
                $res =  $this->verifySign($str, $sign);
                // 签名验证通过
                if ($res) {
                    // 查询充值订单
                    $order_info = db('payment')->where("id = {$data['appOrderNo']} ")->find();
                    // 充值金额判断
                    if ($order_info['amount']*100 == $data['totalAmount'] && !$order_info['status']) {
                        // 开启事务
                        Db::startTrans();
                        $up_payment['cbOrderNo']        = $data['cbOrderNo'];
                        $up_payment['paymentChannel']   = $data['paymentChannel'];
                        $up_payment['outOrderNo']       = $data['outOrderNo'];
                        $up_payment['status']           = '1';
                        $res = model('payment')->save($up_payment,['id' => $data['appOrderNo']]);
                        $change_res = $this->changeUser($order_info);
                        if ($change_res) {
                            // 提交事务
                            Db::commit();
                            die('success');
                        }else{
                            // 事务回滚
                            Db::rollback();
                        } 
                    }
                }else{
                    die('签名不通过！');
                }
            }
        }
    }

    // 支付结果异步轮询
    public function check_ajax(){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $order_info = db('payment')->where("id = {$data['order_id']} ")->find();
            if ($order_info['status'] == '1') {
                show(1,'支付成功',url('Home/User/financeList'));
            }else{
                show(0,'不成功');
            }
        }
    }
    /*异步回调测试*/
    public function test()
    {
        // 回调的数据
        $data = array (
          'sign' => 'gWhiYco+pgJftZy7gp7VwaQ4vnKUSdnhKxfXON2z9A1m9lKG6l/tj/euyP6NhfJIp0YYQiAsnm11ScWSZEynuxExoNX961lf8gaDlayCjmGyDQYxWZIH5LDcnO4TzMLY+W+Vl1DnAFOyIDZZXQuVU4OD15OXz3a21dnoHDQDmztK/XB+wQdvHw8jpaCyM3gZ5c/GJ4RR5ePjC2uDMkQnQ6QMyeH+CDUoLvv4XgK+iNIGS3HMIp2HEkQ5UHZkCRr1u0dIGbL9JNs48H3rSSOgnELf0D83RfDxc35zenW9H6RqGVjG0pzs+fy3BQlcx8oiN8vXduao2L8aKwxbX/91LA==',
          'cbOrderNo' => 'TCWX18061114541129284952',
          'subject' => '开放平台测试账号-开放平台测试门店 消费',
          'paymentChannel' => 'WECHAT',
          'outOrderNo' => '4200000132201806119041357364',
          'totalAmount' => '1',
          'receiveAmount' => '1',
          'appOrderNo' => '7',
          'payTime' => '1528700057369',
          'discountAmount' => '0',
          'orderStatus' => 'PAY_SUC',
          'paymentWay' => 'QRCODE',
        );
        //$url = url('home/payment/notify');
        $url = 'http://www.richs.my/home/payment/notify.html';
        //var_dump($url);die;
        $res = $this->request_post($data,$url);
        var_dump($res);die;
    }

    /**
     * 获取公钥
     * @return bool|resource
     */
    public function getPublicKey()
    {
        $publicKey = '-----BEGIN PUBLIC KEY-----  
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq+iElxN5xzGpN81gjLSz
TROPWvYw+06YPyjG5bufC2NHjoaiISbdw6AnYcdIAT8g5dOgYB4SyDPSxvfje2k9
CTUFbmNTTm5humwwbCz94UVJf6XwAWT1432WtW1VtrC3tK3BTM5v1rY4Bt7yjQPD
/ao4ZGe/RsVOYIT7KGD8g/eLLuWPMcCJmCA0P8Vl65ouS3ioReLMWdEFwTGUNeWf
A14/ki9Z+p1ldSz1uq+YE1eoYF18kyF3nlQbIjHdBhk9bRhodLBLrHP0SndawDUy
6cdO7YbCsP2utYGVkWTxrCezszPhtGDfP9Jvvtw1J1yKCPNtfbDOz1uczhBO/u6P
6QIDAQAB  
-----END PUBLIC KEY-----';
        return openssl_pkey_get_public($publicKey);
    }

    /**
     * 验证签名
     * @param string $data 数据
     * @param string $sign 签名
     * @return bool
     */
    public function verifySign($data = '', $sign = '')
    {
        return (bool)openssl_verify(
                      $data,
                      base64_decode($sign),
                      self::getPublicKey(),
                      OPENSSL_ALGO_SHA256
                    );
    }

    public function request_post($param = '',$url = '') {
        //$url = 'https://openapi.caibaopay.com/gatewayOpen.htm';
        //$url = 'http://openapi.caibaopay.com/gatewayOpen.htm';
        if (empty($url) || empty($param)) {

            return false;
        }
        $postUrl = $url;
        $curlPost = $param;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        
        return $data;
    }
    /**
     * 获取支付信息
     * @param int $uid 用户id
     * @param int $money 支付金额
     * @param int $type 1是增值宝充值 2等级升级
     * @return mixed
     */
    public function getPayInfo($uid,$money,$type,$rank_id='0',$shop_uid='0')
    {
        // 插入充值记录
        $payment['uid']         = $uid;
        $payment['amount']      = $money;
        $payment['time']        = time();
        $payment['type']        = $type;
        $payment['rank_id']     = $rank_id;
        $payment['shop_uid']    = $shop_uid;
        $res        = model('payment')->save($payment);
        $order_id   = model('payment')->getLastInsID();

        // 支付提交的数据
        $post_data['command'] = 'caibao.pay.h5';
        $post_data['app']     = $this->pay_config['app'];
        $post_data['operator_id']     = $this->pay_config['operator_id'];
        $post_data['key']     = $this->pay_config['key'];
        $post_data['amount']  = $money*100;
        $post_data['local_order_no']   = $order_id;
        $post_data['timestamp']        = time();
        $post_data['subject'] = 'goods';
        $post_data['version'] = '1.0';
        $post_data['un_discount_amount']     = '';
        $post_data['notify_url']     = 'http://www.txfdzswvip.com/home/payment/notify.html';
        $post_data['redirect_url']     = '';

        $signString = "amount=".$post_data['amount']."&app=".$post_data['app']."&local_order_no=".$post_data['local_order_no']."&operator_id=".$post_data['operator_id']."&subject=".$post_data['subject']."&timestamp=".$post_data['timestamp']."&key=".$post_data['key'];
        // 生成签名
        $post_data['sign']     = md5($signString);
        // 发送异步请求
        $res = request_post($post_data);
        // json转数组
        $res = json_decode($res,true);
        $res['order_id'] = $order_id;
        return $res;
    }
    /**
     * 支付成功更改用户信息
     * @param int $order_info 用户在线充值信息
     * @return mixed
     */
    public function changeUser($order_info)
    {
        // 充值用户的id
        $uid = $order_info['uid'];
        // 查询用户信息
        $user_info = db('user')->where(" id = {$uid}")->find();
        // 这是增值宝充值
        if ($order_info['type'] == '1') {
            // 更新账户余额宝
            $up_user['balance'] = $user_info['balance'] + $order_info['amount'];
            // 余额宝充值记录
            $log[]  =   array(
                            'num'           => $order_info['amount'],
                            'wallet_type'   => '7',
                            'change_type'   => '13',
                            'time'          => time(),
                            'uid'           => $uid,
                            'before_num'    => $user_info['balance'],
                            'later_num'     => $up_user['balance'],
                            'description'   => '余额宝充值：'.$order_info['amount'].'元',
                        );






        // 用户等级充值
        }elseif($order_info['type'] == '2'){
            // 要升级到该等级的信息
            $up_rank_info  = db('user_rank')->where('id',$order_info['rank_id'])->field('reg_money,reg_integral,rank_name')->find();
            // 目前等级信息 
            $now_rank_info = db('user_rank')->where('id',$user_info['rank_id'])->field('reg_money,reg_integral,rank_name')->find();
            // 升级到现在等级所交金额
            //$up_money = $up_rank_info['reg_money'] - $now_rank_info['reg_money'];
            $up_money = $up_rank_info['reg_money'] - $now_rank_info['reg_money'];
            // 升级到现在等级所赠送激活积分
            $up_reg_integral = $up_rank_info['reg_integral'] - $now_rank_info['reg_integral'];
            // 计算账户激活积分
            $user_up['reg_integral'] = $user_info['reg_integral'] + $up_reg_integral;
            // 赠送激活积分记录
            $reg_log =  array(
                            'num'           => $up_reg_integral,
                            'wallet_type'   => '1',
                            'change_type'   => '12',
                            'time'          => time(),
                            'uid'           => $uid,
                            'before_num'    => $user_info['reg_integral'],
                            'later_num'     => $user_up['reg_integral'],
                            'description'   => $now_rank_info['rank_name'].'升级到'.$up_rank_info['rank_name'].'赠送激活积分'.$up_reg_integral,
                        );
            // 充值记录
            $log =  array(
                            'num'           => $order_info['amount'],
                            'wallet_type'   => '9',
                            'change_type'   => '15',
                            'time'          => time(),
                            'uid'           => $uid,
                            'before_num'    => '0',
                            'later_num'     => '0',
                            'description'   => '激活等级支付'.$order_info['amount'].'元',
                        );
            // 更新用户---id
            $user_up['rank_id'] = $order_info['rank_id'];
            /*推荐关系提成*/
            if ($user_info['share_id'] > 0) {
                // 分享者信息
                $share_user = db('user')->field('re_share_integral')->where('id',$user_info['share_id'])->find();
                // 计算推荐奖励 保留两位
                //$award = $up_money*$this->proConfig['user_share_ratio'];
                $award = sprintf("%.2f", $up_money*$this->proConfig['user_share_ratio']);
                if ($award > 0) {
                    // 计算账户奖励积分
                    $up_share_user['re_share_integral'] = $share_user['re_share_integral'] + $award;
                    // 推荐者资金记录---变动之前的值  
                    $share_log['before_num'] = $share_user['re_share_integral'];
                    // 推荐者资金记录---变动之后的值 
                    $share_log['later_num'] = $up_share_user['re_share_integral'];
                    // 推荐者资金记录---变动值          
                    $share_log['num'] = $award;
                    // 推荐者资金记录---变动的钱包类型 
                    $share_log['wallet_type'] = '6';
                    // 推荐者资金记录---操作类型 
                    $share_log['change_type'] = '10';
                    // 推荐者资金记录---变动时间 
                    $share_log['time'] = time();
                    // 推荐者资金记录---会员id 
                    $share_log['uid'] = $user_info['share_id'];
                    // 推荐者资金记录---变动描述 
                    $share_log['description'] = '推荐的会员'.$user_info['user_name'].'从'.$now_rank_info['rank_name'].'升级到'.$up_rank_info['rank_name'].'奖励'.$award;
                }
            }
            // 更新用户账户
            $user_res = model('user')->save($user_up,['id' => $uid]);
            // 插入的记录
            $all_logs[] = $log;
            $all_logs[] = $reg_log;
            // 有分享的会员
            if ($user_info['share_id'] > 0 && $award > 0) {
                // 更新分享者信息
                $share_user_res = model('user')->save($up_share_user,['id' => $user_info['share_id']]);
                // 奖励记录
                $all_logs[] = $share_log;
                // 插入记录
                $log_res = model('fund_log')->saveAll($all_logs);
                // 数据操作成功
                if ($user_res && $log_res && $share_user_res) {
                    return true; 
                // 数据操作失败
                }else{
                    return false;  
                }
            // 没有分享的会员
            }else{
                $log_res = model('fund_log')->saveAll($all_logs);
                if ($user_res && $log_res) {
                    return true;  
                }else{
                    return false;   
                }
            }




        }elseif($order_info['type'] == '3'){// 线下扫码支付
            // 商户信息
            $shop_info = db('user')->where('id',$order_info['shop_uid'])->field("user_name,shop_money")->find();
            // 更新商家钱包
            $up_shop['shop_money'] = $shop_info['shop_money'] + $order_info['amount'];
            // 重消钱包更新会员
            $up_user['consume_integral'] = $user_info['consume_integral'] + $order_info['amount'];
            // 商户收钱记录
            $log[] =  array(
                                'num'           => $order_info['amount'],
                                'wallet_type'   => '8',
                                'change_type'   => '4',
                                'time'          => time(),
                                'uid'           => $order_info['shop_uid'],
                                'before_num'    => $shop_info['shop_money'],
                                'later_num'     => $up_shop['shop_money'],
                                'description'   => '扫码收钱：'.$order_info['amount'].'，会员：'.$user_info['user_name'],
                            );
            // 会员重消记录
            $log[] =  array(
                            'num'           => $order_info['amount'],
                            'wallet_type'   => '3',
                            'change_type'   => '14',
                            'time'          => time(),
                            'uid'           => $uid,
                            'before_num'    => $user_info['consume_integral'],
                            'later_num'     => $up_user['consume_integral'],
                            'description'   => '线下扫码支付：'.$order_info['amount'].'，赠送重消积分：'.$order_info['amount'],
                        );
            // 会员支付记录
            $log[] =  array(
                            'num'           => '-'.$order_info['amount'],
                            'wallet_type'   => '9',
                            'change_type'   => '5',
                            'time'          => time(),
                            'uid'           => $uid,
                            'before_num'    => '0',
                            'later_num'     => '0',
                            'description'   => '线下扫码支付：'.$order_info['amount'].'，商户：'.$shop_info['user_name'],
                        );
            // 线下消费记录
            $shop_log = array(
                            'num'           => $order_info['amount'],
                            'wallet_type'   => '9',
                            'time'          => time(),
                            'buy_uid'       => $uid,
                            'shop_uid'      => $order_info['shop_uid'],
                        );
            // 更新会员账号
            $up_user_res = model('user')->allowField(true)->save($up_user,['id' => $uid]);
            // 更新商户账号
            $up_shop_res = model('user')->allowField(true)->save($up_shop,['id' => $order_info['shop_uid']]);
            // 插入资金记录
            $log_res = model('fund_log')->saveAll($log);
            // 插入线下消费记录
            $shop_log_res = model('shop')->save($shop_log);
            if ($up_user_res && $up_shop_res && $log_res && $shop_log_res) {
                return true;
            }else{
                return false;
            }

        }else{
            return false;
        }
        // 插入资金记录
        $log_res = model('fund_log')->saveAll($log);
        // 更新会员账号
        $up_user_res = model('user')->allowField(true)->save($up_user,['id' => $order_info['uid']]);
        if ($log_res && $up_user_res) {
            return true;
        }else{
            return false;
        }
    }

    /**
     * 支付二维码页面
     * @return mixed
     */
    public function pay_code()
    {
        $post_url = url('Home/Payment/check_ajax');
        // 二维码支付页面赋值
        return $this->fetch('user/pay_code',['url' => $_GET['url'],'order_id' => $_GET['order_id'],'post_url' => $post_url]);
    }
}
